<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="质检组" prop="groupId">
        <el-select
          v-model="queryParams.groupId"
          placeholder="质检组"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="g in groupList"
            :key="g.id"
            :label="g.groupName"
            :value="g.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ruleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" v-if="false"/>
      <el-table-column label="规则描述" align="center" prop="description" />
      <el-table-column label="规则类型" align="center" prop="rule" :formatter="ruleFormat"  />
      <el-table-column label="规则组" align="center" prop="groupName" />
      <el-table-column label="主题表名" align="center" prop="table" />
      <el-table-column label="字段名" align="center" prop="field" />
      <el-table-column label="是否启用" align="center" prop="isEnable" >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isEnable"
            @change="enable(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949"
            >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime"  width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="规则组" prop="groupId" required>
          <el-select
            v-model="form.groupId"
            placeholder="请选择规则组质检组"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="g in groupList"
              :key="g.id"
              :label="g.groupName"
              :value="g.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据库" prop="database" quality required>
          <el-input value="quality"  v-model="form.database" placeholder="请输入数据库名称" />
        </el-form-item>
        <el-form-item label="待检表名" prop="table" required>
          <el-select
            v-model="form.table"
            placeholder="请选择待检表名"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="d in tableList"
              :key="d.value"
              :label="d.value"
              :value="d.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="字段名" prop="field" required>
          <el-select
            v-model="form.field"
            placeholder="请选择字段名"
            clearable
            style="width: 240px"
          >
            <el-option
              v-if="form.table === 'body_text_data'"
              v-for="d in body_text_data"
              :key="d.id"
              :label="d.value"
              :value="d.id"
            />
            <el-option
              v-if="form.table === 'dict_job'"
              v-for="d in dict_job"
              :key="d.id"
              :label="d.value"
              :value="d.id"
            />
            <el-option
              v-if="form.table === 'weather-data'"
              v-for="d in weather_data"
              :key="d.id"
              :label="d.value"
              :value="d.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规则类型" prop="rule" required>
          <el-select
            v-model="form.rule"
            placeholder="请选择规则类型"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="d in ruleTypeList"
              :key="d.id"
              :label="d.value"
              :value="d.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="begin" prop="begin" v-if="[2].includes(form.rule)">
          <el-input v-model="form.begin" placeholder="begin" />
        </el-form-item>
        <el-form-item label="end" prop="end"  v-if="[2].includes(form.rule)">
          <el-input v-model="form.end" placeholder="end" />
        </el-form-item>
        <el-form-item label="开始时间" prop="begin" v-if="[3].includes(form.rule)">
          <el-date-picker
            v-model="form.begin"
            value-format="timestamp"
            type="datetime"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="end"  v-if="[3].includes(form.rule)">
          <el-date-picker
            v-model="form.end"
            value-format="timestamp"
            type="datetime"
            placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="正则" prop="patten"  v-if="[4].includes(form.rule)">
          <el-input v-model="form.patten" placeholder="正则" />
        </el-form-item>
        <el-form-item label="规则描述" prop="description" required>
          <el-input v-model="form.description" placeholder="请输入规则描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRule, getRule, delRule, addRule, updateRule , enable} from "@/api/business/rule/rule";
import {all} from "@/api/business/group/group";

export default {
  name: "Rule",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      ruleList: [],
      // 分组列表
      groupList: [],
      // 规则类型
      ruleTypeList: [
        {
          id:1,
          value:"非空字符串"
        },
        {
          id:2,
          value:"数据范围检查"
        },
        {
          id:3,
          value:"日期范围检查"
        },
        {
          id:4,
          value:"正则表达式"
        }
      ],
      // 数据库列表
      databaseList: [
        {
          value:"quality"
        }
      ],
      // 表列表
      tableList: [
        {
          value:"body_text_data"
        },
        {
          value:"dict_job"
        },
        {
          value:"weather-data"
        }
      ],
      // body_text_data表字段
      body_text_data:[
        {
          id:"class_name",
          value:"class_name(String)"
        },
        {
          id:"sno",
          value:"sno(int)"
        },
        {
          id:"sex",
          value:"sex(String)"
        },
        {
          id:"sum_grade",
          value:"sum_grade(double)"
        },
        {
          id:"standard_grade",
          value:"standard_grade(int)"
        },
        {
          id:"height",
          value:"height(double)"
        },
        {
          id:"weight",
          value:"weight(double)"
        },
        {
          id:"VC",
          value:"VC(int)"
        },
        {
          id:"eightHundred",
          value:"800M(String)"
        },
        {
          id:"oneThousand",
          value:"1000M(String)"
        },
        {
          id:"fifty",
          value:"50M(String)"
        },
        {
          id:"long_jump",
          value:"long_jump(double)"
        },
        {
          id:"sitting_forward_bend",
          value:"sitting_forward_bend(double)"
        },
        {
          id:"sit_up",
          value:"sit_up(int)"
        }
      ],
      // dict_job表字段
      dict_job: [
        {
          id:"job_name",
          value:"job_name(String)"
        },
        {
          id:"job_code",
          value:"job_code(String)"
        },
        {
          id:"parent_code",
          value:"parent_code(String)"
        },
        {
          id:"parent_name",
          value:"parent_name(String)"
        },
        {
          id:"level",
          value:"level(int)"
        },
        {
          id:"code",
          value:"code(String)"
        },
        {
          id:"name_path",
          value:"name_path(String)"
        }
      ],
      // weather-data表字段
      weather_data: [
        {
          id:"data_time",
          value: "data_time(Data)"
        },
        {
          id:"qualitylevel",
          value: "qualitylevel(String)"
        },
        {
          id:"AQI",
          value: "AQI(int)"
        },
        {
          id:"AQI_Rank",
          value: "AQI_Rank(int)"
        },
        {
          id:"PM25",
          value: "PM2.5(int)"
        },
        {
          id:"PM10",
          value: "PM10(int)"
        },
        {
          id:"SO2",
          value: "SO2(int)"
        },
        {
          id:"NO2",
          value: "NO2(int)"
        },
        {
          id:"CO",
          value: "CO(double)"
        },
        {
          id:"O3",
          value: "O3(int)"
        }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: null,
        database: null,
        type: null,
        table: null,
        field: null,
        rule: null,
        patten: null,
        isEnable: null,
        description: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        groupId: [
          { required: true, message: "分组不能为空", trigger: "blur" }
        ],
        database: [
          { required: true, message: "数据库不能为空", trigger: "blur" }
        ],
        table: [
          { required: true, message: "主题表名不能为空", trigger: "blur" }
        ],
        field: [
          { required: true, message: "字段名不能为空", trigger: "blur" }
        ],
        rule: [
          { required: true, message: "规则类型不能为空", trigger: "blur" }
        ],
        description: [
          { required: true, message: "规则描述不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      this.getGroupList();
      listRule(this.queryParams).then(response => {
        this.ruleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getGroupList(){
      all().then(response => {
        this.groupList = response.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        groupId: null,
        database: 'quality',
        type: null,
        table: null,
        field: null,
        rule: null,
        patten: null,
        isEnable: null,
        description: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加质检规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRule(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改质检规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的数据吗？').then(function() {
        return delRule(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /**
     * 规则类型转换
     * @param row
     * @returns {string}
     */
    ruleFormat(row){
      for (let i = 0; i < this.ruleTypeList.length; i++) {
        if (row.rule === this.ruleTypeList[i].id){
          return this.ruleTypeList[i].value;
        }
      }
    },
    /**
     * 启用/停用规则
     * @param row
     */
    enable(row){
      let flag = row.isEnable;
      row.isEnable = !row.isEnable;
      let msg = flag ? "是否要启用当前规则" : "是否要停用当前规则";
      this.$modal.confirm(msg).then(function() {
        enable(row.id);
        if (flag){
          row.isEnable = true
          // 逻辑处理
          this.$message.success('打开成功!')
        }else{
          row.isEnable = false
          // 逻辑处理
          this.$message.success('关闭成功！')
        }
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("设置成功");
      }).catch(() => {});
    }
  }
};
</script>
